package com.zhang.utils;

import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import org.xmlpull.v1.XmlPullParserException;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Configuration
@EnableConfigurationProperties(MinioProperties.class)
public class MinioUploader {
    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;
    //启动项目的时候初始化minioClient
    @Bean
    public MinioClient minioClient() throws Exception{
        //使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
        MinioClient minioClient = new MinioClient(minioProperties.getEndpoint(), minioProperties.getAccessKey(), minioProperties.getSecretKey());
        //检查存储桶是否已经存在
        boolean isExist = minioClient.bucketExists(minioProperties.getBucketName());
        if(!isExist) {
            //创建一个名为asiatrip的存储桶，用于存储照片的zip文件。
            minioClient.makeBucket(minioProperties.getBucketName());
        }
        return minioClient;
    }
    public String uploadFile(MultipartFile file) throws Exception {
        //使用putObject上传一个文件到存储桶中D:\HighlevelSpring\LastManager\day03\白色4.jpg
        String filename = UUID.randomUUID().toString()+file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        PutObjectOptions putObjectOptions = new PutObjectOptions(inputStream.available(),-1);
        putObjectOptions.setContentType(file.getContentType());
        minioClient.putObject(minioProperties.getBucketName(),filename,inputStream,putObjectOptions);
        //http://139.196.214.189:9000/java1018/new.jpg
        String retUrl=minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+filename;
        return retUrl;
    }
}
